package com.bruce.tool.netty.socket.netty.chat;

import com.bruce.tool.common.util.string.StringUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Sharable
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private ChannelGroup group;

    public ChatServerHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 添加渠道
        group.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 删除渠道
        group.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        if (StringUtils.isEmpty(msg)){
            return;
        }
        Channel incoming = ctx.channel();
        for (Channel channel : group) {
            if (channel != incoming){ // 和当前渠道不同的渠道,则发送消息;原因,目前的socketclient只有2个,一个作为通信的服务器方,一个作为通信的客户方
                channel.writeAndFlush(msg + "\n");
            }
        }
    }

}